package com.zhenyi.fenda.controller;

import java.util.Date;
import java.util.Map;

import org.joda.time.DateTime;

import com.fenda.common.model.FdConsult;
import com.fenda.common.model.FdMaster;
import com.fenda.common.model.FdNotification;
import com.fenda.common.model.FdOrder;
import com.fenda.common.model.FdQuestion;
import com.fenda.common.model.FdRoom;
import com.fenda.common.model.FdUser;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.utils.interceptor.TestInterceptor;
import com.wxpay.utils.MD5Util;
import com.zhenyi.fenda.core.Encrypt;

import cn.hutool.core.codec.Base64;

public class BillController extends FDController {

	private Map<String, String> getDeResult(String en) {
		String key = MD5Util.MD5Encode(PARTNER_KEY, "utf-8");
		String de = Encrypt.Aes256Decode(Base64.decode(en), key.getBytes());
		Map<String, String> result = PaymentKit.xmlToMap(de);
		return result;
	}

	@Clear
	@Before(Tx.class)
	public void billPush() {
		// try {
		String xmlResult = HttpKit.readData(getRequest());
		if (StrKit.isBlank(xmlResult)) {
			renderPayFail();
			return;
		}
		// if (DEBUG) {
		// LogKit.info(xmlResult);
		// }
		Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
		// String appid = result.get("appid");
		String bank_type = result.get("bank_type");
		String cash_fee = result.get("cash_fee");
		String fee_type = result.get("fee_type");
		String is_subscribe = result.get("is_subscribe");
		// String mch_id = result.get("mch_id");
		// String nonce_str = result.get("nonce_str");
		// String openid = result.get("openid");
		String out_trade_no = result.get("out_trade_no");
		String result_code = result.get("result_code");
		String return_code = result.get("return_code");
		String sign = result.get("sign");
		String time_end = result.get("time_end");
		String total_fee = result.get("total_fee");
		String trade_type = result.get("trade_type");
		String transaction_id = result.get("transaction_id");
		String attach = result.get("attach");
		if (!"SUCCESS".equals(return_code)) {
			LogKit.warn("返回失败 " + out_trade_no);
			renderPaySuccess();
			return;
		}
		if (!"SUCCESS".equals(result_code)) {
			LogKit.warn("支付结果失败 " + out_trade_no);
			renderPaySuccess();
			return;
		}
		System.out.println(JsonKit.toJson(result));
		// System.out.println("--------");
		// System.out.println(JsonKit.toJson(result));
		// System.out.println("out_trade_no: " + out_trade_no);
		// System.out.println("total_fee: " + total_fee);
		// System.out.println("cash_fee: " + cash_fee);
		// System.out.println("out_trade_no: " + out_trade_no);
		// System.out.println("--------");

		String partnerKey = PARTNER_KEY;
		String mySign = PaymentKit.createSign(result, partnerKey);
		if (!mySign.equals(sign)) {
			// order.setVerify(1);
			LogKit.warn("Sign失败 " + out_trade_no);
			renderPayFail();
			return;
		} else {
			// order.setVerify(0);
		}
		onPaySuccess(out_trade_no);
		renderPaySuccess();
	}

	@Clear
	@Before(TestInterceptor.class)
	public void pay() {
		String orderNo = getPara("orderNo");
		onPaySuccess(orderNo);
		renderPaySuccess();
	}

	private void renderPayFail() {
		String returnXML = "<xml>\n" + "<return_code><![CDATA[FAIL]]></return_code>\n"
				+ "<return_msg><![CDATA[FAIL]]></return_msg>\n" + "</xml>";
		renderText(returnXML, "text/xml");
	}

	private void renderPaySuccess() {
		String returnXML = "<xml>\n" + "<return_code><![CDATA[SUCCESS]]></return_code>\n"
				+ "<return_msg><![CDATA[OK]]></return_msg>\n" + "</xml>";
		renderText(returnXML, "text/xml");
	}

	private FdRoom createChatRoom() {
		FdRoom room = new FdRoom();
		room.setExpire(new DateTime().plusMinutes(60).toDate());
		room.save();
		room.setCode(hashId.encode(room.getId()));
		room.update();
		return room;
	}

	private void onPaySuccess(String orderNo) {
		FdOrder order = FdOrder.dao.searchFirst("orderNo", orderNo);
		FdConsult consult = FdConsult.dao.searchFirst("orderId", order.getId());
		if (consult != null) {
			if (consult.getRoomId() == null) {
				consult.print();
				FdRoom room = createChatRoom();
				room.setUserId(order.getUserId());
				room.setMasterId(consult.getMasterId());
				room.update();
				consult.setRoomId(room.getId());
				consult.update();
			}
			Long mastetId = consult.getMasterId();
			FdMaster master = FdMaster.dao.findById(mastetId);
			master.setPaidCount(master.getPaidCount() + 1);
			master.update();
		}
		FdQuestion question = FdQuestion.dao.searchFirst("orderId", order.getId());
		if (question != null) {
		}
		order.setStatus(1);
		order.update();

		FdUser user = FdUser.dao.findById(order.getUserId());
		user.setCoin(user.getCoin() + order.getPrice());// 更新测币数
		user.update();

		FdNotification fdNotification = new FdNotification();
		fdNotification.setUserId(user.getId());
		fdNotification.setContent("支付成功提醒");
		fdNotification.setAddTime(new Date());
		fdNotification.setType(NOTIFICACATION_PAY);
		fdNotification.save();

		renderSuccess();
	}

}
